<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\func\Transaction;
use app\common\model\Allocation;
use app\common\model\AppVersion;
use app\common\model\Cash;
use app\common\model\Flow;
use app\common\model\OrderProduct;
use app\common\model\Policy;
use app\common\model\PolicyCash;
use app\common\model\PolicyRelation;
use app\common\model\PolicySimcard;
use app\common\model\PolicyStandard;
use app\common\model\Profit;
use app\common\model\Stardard;
use fast\Random;
use think\Db;
use think\Exception;

class Setting extends Api
{
    protected $noNeedLogin = "*";
    protected $noNeedRight = '*';
    protected $typeArr = [0, 1, 2]; //上级类型：1=机构，2=代理

    public function getProductAllocationCount(){
        $productList = Lib::getMyProduct5($this->auth->id,2);
        foreach ($productList as $key => &$val){
            $val["total"] = Lib::getAllocationCount5(2,$this->auth->id,$val['id']);
            unset($val['table_name']);
        }
        unset($val);

        $this->success("产品调拨统计",$productList);
    }

    //修改下级代理默认政策
    public function setBelowPolicy()
    {
        $userId = $this->request->post("user_id");
        $relationId = $this->request->post("relation_id");
        $productId = $this->request->post("product_id");

        if (!$userId || !$relationId || !$productId) {
            $this->error("缺少参数！");
        }

        $stock = Lib::getStocks(2, $userId, $productId);
        if ($stock && $stock->stocks != 0) {
            $this->error("代理库存未清，不允许调整政策！");
        }

        $childs = Tools::getUserChild($userId, 3);
        if (count($childs) > 0) {
            foreach ($childs as $key => $val) {
                $childStock = Lib::getStocks(2, $val['id'], $productId);
                if ($childStock && $childStock->stocks != 0) {
                    $this->error("代理下级【{$val['name']}】库存未清，不允许调整政策！");
                }
            }
        }

        $result = false;
        Db::startTrans();
        try {
            PolicyRelation::where(["main_type" => 2, "main_id" => $userId, "product_id" => $productId])->update(["default" => 0]);

            $relation = PolicyRelation::get($relationId);
            $relation->default = 1;
            $relation->default_time = time();
            $result = $relation->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($result == false) {
            $this->error("设置失败！");
        }

        $this->success("设置成功！");
    }

    //查询下级产品政策
    public function getBelowPolicy()
    {
        $userId = $this->request->post("user_id");

        if (!$userId) {
            $this->error("缺少参数！");
        }

        $product = Lib::getUserProduct(2, $userId, 'all');

        if (count($product) > 0) {
            foreach ($product as $key => &$val) {
                $val["policy"] = Lib::getUserPolicy(2, $userId, $val['id']);
            }
            unset($val);
        }

        $this->success("下级代理产品政策", $product);
    }

    public function savePolicySetting()
    {
        $param = $this->request->post();

        if (!$param['title'] || !$param['top_policy_id'] || !$param['product_id']) {
            $this->error("缺少参数！");
        }

        if (!$param['card_type'] || !$param['transaction_type_ids'] || !$param['rate_ids'] || !$param['channel_ids']) {
            $this->error("基本设置必选！");
        }

        if (count($param['profit_base']) == 0 && count($param['profit_hide']) == 0) {
            $this->error("分润设置未设置！");
        }

        if ($param['cash_base'] == "" && $param['cash_hide'] == "") {
            $this->error("返现未设置！");
        }

        if ($param['flow_base'] == "" && $param['flow_hide'] == "") {
            $this->error("流量卡未设置！");
        }

        Db::startTrans();
        try {
            $policy = new \app\common\model\Policy();
            $policy->main_type = 2;
            $policy->main_id = $this->auth->id;
            $policy->top_policy_id = $param['top_policy_id'];
            $policy->title = $param['title'];
            $policy->product_id = $param['product_id'];
            $policy->card_type = $param['card_type'];
            $policy->transaction_type_ids = $param['transaction_type_ids'];
            $policy->rate_ids = $param['rate_ids'];
            $policy->channel_ids = $param['channel_ids'];
            $policy->status = 1;
            $res = $policy->save();

            if ($res) {
                for ($i = 0; $i < count($param['card']); $i++) {
                    $detail = Lib::getPolicyProfitByParams($policy->id, $param['card'][$i], $param['tran'][$i], $param['rate'][$i], $param['channel'][$i]);
                    if ($detail) {
                        if ($detail->profit_base == $param['profit_base'][$i] && $detail->profit_hide == $param['profit_hide'][$i]) {
                            continue;
                        } else {
                            $detail->profit_base = $param['profit_base'][$i] == "" ? 0 : $param['profit_base'][$i];
                            $detail->profit_hide = $param['profit_hide'][$i] == "" ? 0 : $param['profit_hide'][$i];
                            $detail->save();
                        }
                    } else {
                        $details = new \app\common\model\PolicyProfit();
                        $details->policy_id = $policy->id;
                        $details->card_type = $param['card'][$i];
                        $details->transaction_type_id = $param['tran'][$i];
                        $details->rate_id = $param['rate'][$i];
                        $details->channel_id = $param['channel'][$i];
                        $details->profit_base = $param['profit_base'][$i] == "" ? 0 : $param['profit_base'][$i];
                        $details->profit_hide = $param['profit_hide'][$i] == "" ? 0 : $param['profit_hide'][$i];
                        $details->save();
                    }
                }

                $cash = new PolicyCash();
                $cash->policy_id = $policy->id;
                $cash->day_limit = $param['cash_limit'];
                $cash->money = $param['cash_money'];
                $cash->base = $param['cash_base'];
                $cash->hide = $param['cash_hide'];
                $cash->save();

                $flow = new PolicySimcard();
                $flow->policy_id = $policy->id;
                $flow->base = $param['flow_base'];
                $flow->hide = $param['flow_hide'];
                $flow->save();

                if (count($param['standard_limit']) > 0) {
                    $standardData = [];
                    for ($i = 0; $i < count($param['standard_limit']); $i++) {
                        $standardData[] = [
                            "policy_id" => $policy->id,
                            "day_limit" => $param['standard_limit'][$i],
                            "money" => $param['standard_money'][$i],
                            "base" => $param['standard_base'][$i],
                            "hide" => $param['standard_hide'][$i],
                        ];
                    }
                    $standard = new PolicyStandard();
                    $standard->saveAll($standardData);
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("设置成功！");
    }

    public function checkSetting()
    {
        $policyId = $this->request->post('policy_id');
        $cardId = $this->request->post('card_id');
        $tranId = $this->request->post('tran_id');
        $rateId = $this->request->post('rate_id');
        $channelId = $this->request->post('channel_id');

        $profit = Lib::getPolicyProfit($policyId, $cardId, $tranId, $rateId, $channelId);

        if (!$profit) {
            $this->error("请联系上级设置分润");
        }

        $this->success("", ["base" => $profit->profit_base, "hide" => $profit->profit_hide]);
    }

    public function getPolicySetting()
    {
        $productId = $this->request->post("product_id");
        $info = [];

        $defaultPolicy = Lib::getDefaultPolicy(2, $this->auth->id, $productId);
        if (!$defaultPolicy) {
            $this->error("该产品未设置默认政策，请联系上级");
        }
        $policy = Lib::getPolicy($defaultPolicy->policy_id);
        if (!$policy) {
            $this->error("政策不存在，请联系上级");
        }

        $cardList = Tools::getCardTypeObj($policy->card_type);
        $tranList = Lib::getTransactionTypeBYIds($policy->transaction_type_ids);
        $rateList = Lib::getRateListByIds($policy->rate_ids);
        $channelList = Lib::getChannelByIds($policy->channel_ids);

        $cash = Lib::getPolicyCash($policy->id);
        $flow = Lib::getPolicyFlow($policy->id);
        $standard = Lib::getPolicyStandard($policy->id);

        $info["policy_id"] = $policy->id;
        $info["card_list"] = $cardList;
        $info["tran_list"] = $tranList;
        $info["rate_list"] = $rateList;
        $info["channel_list"] = $channelList;
        $info["cash"] = $cash;
        $info["flow"] = $flow;
        $info["standard"] = $standard;

        $this->success("新建政策", $info);
    }

    //-------------------------设备回退相关--------------------------------

    public function acceptRollback()
    {
        $id = $this->request->post("id");

        $rollback = Lib::getAllocationById($id);
        if (!$rollback) {
            $this->error("未找到回退申请！");
        }
        if ($rollback->to_type != 2 || $rollback->to != $this->auth->id) {
            $this->error("权限不足！");
        }

        $snList = explode(",", $rollback->sn);
        if (count($snList) == 0) {
            $this->error("缺少回退机具信息！");
        }

//        $policy = Lib::getPolicy($rollback->policy_id);
//        if (!$policy) {
//            $this->error("政策不存在，请联系上级！");
//        }

        $data = []; //调拨数据
//        $stocksData = []; //库存数据
        for ($i = 0; $i < count($snList); $i++) {
            $sn = trim($snList[$i]);
            $equip = Lib::getEquip($sn);
            if (!$equip) {
                $this->error("设备未入库！");
            }

            if ($equip && $equip->binding_time > 0) {
                $this->error("已绑定设备，无法回退！");
            }

            $data[] = [
                "allocation_id" => $rollback->id,
                "sn" => $sn
            ];
//            $stocksData[] = $sn;
        }
//        $stocksData = array_unique($stocksData);

        Db::startTrans();
        try {
            //保存操作记录
            $rollback->confirm_type = 1;
            $rollback->confirm_time = time();
            $rollback->save();

            //保存调拨明细
            $details = new \app\common\model\AllocationDetails();
            $details->saveAll($data);

            //更新设备归属
            Tools::updateEquipInfo($data, $rollback->to_type, $rollback->to);

            //目标机构（代理）增加库存
//            Tools::updateStocks($rollback->to_type, $rollback->to, $policy->product_id, 1, $stocksData, "设备调拨增加库存",2);
//
            //减少调拨机构库存
//            Tools::updateStocks($rollback->from_type, $rollback->from, $policy->product_id, 2, $stocksData, "设备调拨减少库存", 2);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("接收成功！");
    }

    public function saveRollback()
    {
        $snList = $this->request->post("sn/a");
        $productId = $this->request->post('product_id');
        $remark = $this->request->post('remark');

        if(!$productId){
            $this->error("缺少产品ID");
        }

        $snList = array_unique($snList);
        if (count($snList) == 0) {
            $this->error("缺少数据！");
        }

        $parent = Tools::getParentInfo(2, $this->auth->id);
        if (count($parent) == 0) {
            $this->error("上级不存在！");
        }

//        $defaultPolicy = Lib::getDefaultPolicy($parent['type'], $parent['obj']->id, $productId);
//        if (!$defaultPolicy) {
//            $this->error("接收机构未设置产品默认政策！");
//        }

//        $stock = Lib::getStocks(2, $this->auth->id, $productId);
//        if ($stock->stocks < count($snList)) {
//            $this->error("产品库存不足！");
//        }

        $allocationList = Lib::getUserAllocationList(2, $this->auth->id, [1, 2]);
        $list = [];
        foreach ($allocationList as $k => $v) {
            if ($v->data_type != 1) {
                $snLists = explode(",", $v->sn);
                $list = array_merge($list, $snLists);
            }
        }

        foreach ($snList as $key => $val) {
            $equip = Lib::getEquip($val);
            if (!$equip) {
                $this->error("设备不存在！");
            }
            if ($equip->binding_time > 0) {
                $this->error("已绑定设备，无法回退！");
            }

            if ($equip->main_type != 2 || $equip->main_id != $this->auth->id) {
                $this->error("设备【{$val}】不属于您！！");
            }

            if ($productId != $equip->product_id) {
                $this->error("设备不属于一个产品，请确认设备！！");
            }
            if (in_array($val, $list)) {
                $this->error("设备【{$val}】正在调拨中！！");
            }
        }

        $rollback = new Allocation();
        $rollback->type = 2;
        $rollback->from_type = 2;
        $rollback->from = $this->auth->id;
        $rollback->to_type = $parent['type'];
        $rollback->to = $parent['obj']->id;
        $rollback->product_id = $productId;
        $rollback->number = count($snList);
        $rollback->data_type = 3;
        $rollback->sn = implode(",", $snList);
        $rollback->remark_content = $remark;
        $res = $rollback->save();

        if ($res) {
            $this->success("回退成功！");
        } else {
            $this->error("回退失败！");
        }
    }

    public function getFreeEquip()
    {
        $productId = $this->request->post("product_id");

        $freeEquip = Lib::getUserFreeEquip(2, $this->auth->id, $productId);
        $list = [];
        $freeList = [];
        if (count($freeEquip) > 0) {
            $allocationList = Lib::getUserAllocationList(2, $this->auth->id, [1, 2]);
            if (count($allocationList) > 0) {
                foreach ($allocationList as $key => $val) {
                    if ($val->data_type != 1) {
                        $sn = explode(",", $val->sn);
                        $list = array_merge($list, $sn);
                    }
                }
            }
        }

        foreach ($freeEquip as $key => $val) {
            if (!in_array($val->sn, $list)) {
                $freeList[] = $val->sn;
            }
        }

        $this->success("空闲设备列表", $freeList);
    }

    public function getEquipProductList()
    {
        $list = Lib::getEquipProduct(2, $this->auth->id);

        $this->success("所有设备拥有的产品列表", $list);
    }
    //-------------------------设备回退相关--------------------------------

    public function getStandardDetail()
    {
        $standardId = $this->request->post("id");

        $standard = Lib::getStandardById($standardId);

        $this->success("达标详情", $standard);
    }

    public function getFlowDetail()
    {
        $flowId = $this->request->post("id");

        $flow = Lib::getFlowById($flowId);

        $this->success("流量卡详情", $flow);
    }

    public function getCashDetail()
    {
        $cashId = $this->request->post("id");

        $cash = Lib::getCashById($cashId);

        $this->success("返现详情", $cash);
    }

    public function getProfitDetail()
    {
        $profitId = $this->request->post("id");

        $profit = Lib::getProfitById($profitId);

        $this->success("分润详情", $profit);
    }

    public function saveStandards()
    {
        $params = $this->request->post("data/a");
        $productId = $this->request->post('product_id');
        $rateIds = $this->request->post('rate_ids');
        $tran = $this->request->post('transaction_type_ids');
        $cardType = $this->request->post('card_type');
        $channel = $this->request->post('channel_ids');

        if (count($params) > 0) {
            $info = [];
            foreach ($params as $key => $val) {
                if (!$val['title'] || !$val['day_limit'] || !$val['money'] || !$val['reward']) {
                    $this->error("缺少参数！");
                }
                $info[] = [
                    "main_type" => 2,
                    "main_id" => $this->auth->id,
                    "title" => $val['title'],
                    "day_limit" => $val['day_limit'],
                    "money" => $val['money'],
                    "reward" => $val['reward'],
                    "product_id" => $productId,
                    "rate_ids" => $rateIds,
                    "transaction_type_ids" => $tran,
                    "card_type" => $cardType,
                    "channel_ids" => $channel,
                ];
            }
            $standard = new Stardard();
            $result = $standard->allowField(true)->saveAll($info);

            if ($result) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        } else {
            $this->error("缺少数据！");
        }
    }

    public function getStandardSetting()
    {
        $standardId = $this->request->post('standard_id');

        if (!$standardId) {
            $this->error("缺少参数！");
        }

        $standard = Lib::getStandardByIds($standardId);

        if (!$standard) {
            $this->error("该请联系上级进行设置!");
        }

        $this->success("达标设置", $standard);
    }

    public function getSuperProfit()
    {
        $profitId = $this->request->post('profit_id');

        if (!$profitId) {
            $this->error("缺少参数！");
        }

        $profit = Lib::getProfitById($profitId);

        if (!$profit) {
            $this->error("设置不存在，请联系管理员！");
        }

        $details = Lib::getProfitDetails($profit->id);
        if (!$details) {
            $this->error("该政策未设置分润金额，请联系上级!");
        }

        foreach ($details as $key => $val) {
            if (!$val->profit_rate) {
                $this->error("该政策未设置分润金额，请联系上级!");
            }
        }

        $profit->product = Lib::getProductById($profit->product_id);
        $profit->rate_list = Lib::getRateListByIds($profit->rate_ids);
        $profit->tran_list = Lib::getTransactionTypeBYIds($profit->transaction_type_ids);
        $profit->card_type_list = Tools::getCardTypeObj($profit->card_type);
        $profit->channel_list = Lib::getChannelByIds($profit->channel_ids);

        $this->success("分润设置设置", $profit);
    }

    public function getCashSetting()
    {
        $cashId = $this->request->post('cash_id');

        if (!$cashId) {
            $this->error("缺少参数！");
        }

        $cash = Lib::getCashById($cashId);

        if (!$cash) {
            $this->error("该请联系上级进行设置!");
        }

        $this->success("返现设置", $cash);
    }

    public function getFlowSetting()
    {
        $flowId = $this->request->post('flow_id');

        if (!$flowId) {
            $this->error("缺少参数！");
        }

        $flow = Lib::getFlowById($flowId);

        if (!$flow) {
            $this->error("该请联系上级进行设置!");
        }

        $this->success("流量卡设置", $flow);
    }

    public function getSettingPolicy()
    {
        $list = Lib::getPolicyRelationList(2, $this->auth->id);

        $this->success("用户绑定政策", $list);
    }

    //拒绝调拨
    public function denyAllocation()
    {
        $id = $this->request->post('id');
        $remark = $this->request->post('remark');

        $allocation = Lib::getAllocationById($id);
        if (!$allocation) {
            $this->error("调拨申请不存在！");
        }

        $allocation->confirm_type = 2;
        $allocation->confirm_time = time();
        $allocation->confirm_content = $remark;
        $result = $allocation->save();

        if ($result) {
            $this->success("操作成功！");
        } else {
            $this->error("操作失败！");
        }
    }

    public function allocationDetails()
    {
        $id = $this->request->post('id');
        $row = Lib::getAllocationById($id);

        $list = [];
        if ($row->confirm_type == 1) {
            $data = Lib::getAllocationDetails($row->id);
            foreach ($data as $key => $val) {
                $list[] = ["sn" => $val->sn];
            }
        } else {
            if ($row->data_type == 1) {
                $fileData = Tools::importExcel($row->file_url);
                for ($i = 1; $i < count($fileData); $i++) {
                    $list[] = [
                        "sn" => $fileData[$i][0]
                    ];
                }
            } elseif ($row->data_type == 2) {
                $list[] = [
                    "sn" => $row->sn
                ];
            } elseif ($row->data_type == 3) {
                $list = explode(",", $row->sn);
            }
        }

        $this->success("调拨设备详情", $list);
    }

    //接收调拨
    public function acceptAllocation()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error("缺少必要参数");
        }

        $allocation = Lib::getAllocationById($id);
        if (!$allocation || $allocation->to != $this->auth->id) {
            $this->error("调拨申请不存在！");
        }

        $snList = [];
        if ($allocation->data_type == 1) {
            $fileData = Tools::importExcel($allocation->file_url);
            for ($i = 1; $i < count($fileData); $i++) {
                $sn = trim($fileData[$i][0]);
                if ($allocation->type == 1) {
                    $equip = Lib::getAllocationBySn($sn, $allocation->id);
                    if ($equip) {
                        $this->error("设备：{$sn}已入库！");
                    }
                }
                $snList[] = $sn;
            }
        } else {
            $snList = explode(",", $allocation->sn);
        }

        if (count($snList) == 0) {
            $this->error("未查到设备数据！");
        }

        $data = []; //调拨数据
        $stocksData = []; //库存数据
        foreach ($snList as $key => $val) {
            $equipObj = Lib::getEquip($val);
            if (!$equipObj) {
                $this->error("设备【{$val}】未录入库存！");
            }
            if ($allocation->type == 1) {
                $equip = Lib::getAllocationBySn($val, $allocation->id);
                if ($equip) {
                    $this->error("设备：【{$val}】已入库！");
                }
            }
            $data[] = [
                "allocation_id" => $allocation->id,
                "sn" => $val
            ];
            $stocksData[] = $val;
        }

//        $policyId = $allocation->policy_id;
//        $policy = Lib::getPolicy($policyId);
//        if (!$policy) {
//            $this->error("政策不存在，请联系上级！");
//        }


//        $stocksData = array_unique($stocksData);
        Db::startTrans();
        try {
            //保存操作记录
            $allocation->confirm_type = 1;
            $allocation->confirm_time = time();
            $allocation->save();

            //调拨类型为订单，修改订单产品调拨状态
            if($allocation->type_enum == "order"){
                $orderProduct = OrderProduct::where(['order_id' => $allocation->order_id,'product_id' => $allocation->product_id])->find();
                $orderProduct->status = 2;
                $orderProduct->save();
            }

            //保存调拨明细
            $details = new \app\common\model\AllocationDetails();
            $details->saveAll($data);

            //更新设备归属
            Tools::updateEquipInfo($data, $allocation->to_type, $allocation->to);

            if($allocation->order_id > 0){
                $order = \app\common\model\Order::get($allocation->order_id);
                if($order->pay_state == 1){
                    $order->pay_state = 2;
                    $order->save();
                }
            }

            //目标机构（代理）增加库存
//            Tools::updateStocks($allocation->to_type, $allocation->to, $policy->product_id, 1, $stocksData, "设备调拨增加库存",1);

            //减少调拨机构库存
//            Tools::updateStocks($allocation->from_type, $allocation->from, $policy->product_id, 2, $stocksData, "设备调拨减少库存", 1);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("接收成功");
    }

    //调拨列表
    public function getAllocationList()
    {
        $pageSize = $this->request->post('page_size', 15);
        $productId = $this->request->post('product_id');
        $allocationType = $this->request->post('type', 2);
        $search = $this->request->post('name');
        $confirm = $this->request->post('confirm_type', 1);

        if(!$productId){
            $this->error("缺少产品ID");
        }

        $list = Lib::getAllocationList(2, $this->auth->id,$productId, $allocationType, $confirm, $pageSize, $search);

        $list = $list->items();
        foreach ($list as $key => &$val) {
            $snList = [];
            if ($val['data_type'] == 1) {
                if ($confirm != 1) {
                    $fileData = Tools::importExcel($val['file_url']);
                    for ($i = 1; $i < count($fileData); $i++) {
                        $sn = trim($fileData[$i][0]);
                        $snList[] = $sn;
                    }
                } else {
                    $dataList = Lib::getAllocationDetails($val['id']);
                    foreach ($dataList as $k => $v) {
                        $snList[] = $v->sn;
                    }
                }
            } else {
                $snList = explode(",", $val['sn']);
            }
            $fromInfo = Tools::getMainInfoApi($val['from_type'], $val['from']);
            $val['from_info'] = $fromInfo['data'];
//            $val['product'] = Lib::getProductById($val['product_id']);
            $val['sn'] = $snList;
            $val["nickname"] = $val["to_type"] == 2 ? $val["nickname"] : $val["name"] ;
        }
        unset($val);

        $this->success("调拨列表", ["data" => $list]);
    }

    //调拨提交
    public function saveAllocation()
    {
        $orderId = $this->request->post('order_id');
        $productId = $this->request->post('product_id');
        $sn = $this->request->post('sn/a');
        $remark = $this->request->post('remark');

        $sn = array_unique($sn);
        $countSn = count($sn);
        $type = 1;

        if(!$orderId){
            $this->error("缺少订单ID");
        }

        if ($countSn == 0) {
            $this->error("缺少SN");
        }

        if (!$productId) {
            $this->error("缺少参数:调拨产品！");
        }

        $orderProduct = \app\common\func\Order::getOrderProductById($orderId);
        $order = \app\common\func\Order::getOrderById($orderProduct->order_id);
        if($orderProduct->number != $countSn){
            $this->error("发货产品数量不符！");
        }
        $to = $order->user_id;

        if($order->pay_state != 1){
            $this->error("订单无需发货！");
        }

        if ($countSn > 0) {
            foreach ($sn as $key => $val) {
                $equip = Lib::getEquip($val);
                if (!$equip) {
                    $this->error("设备【{$val}】不存在！");
                }
                if ($equip->binding_time > 0) {
                    $this->error("设备【{$val}】已绑定，无法调拨！");
                }

                if ($equip->main_type != 2 || $equip->main_id != $this->auth->id) {
                    $this->error("设备【{$val}】不属于您，请更换其他设备！！");
                }

                if ($productId != $equip->product_id) {
                    $this->error("设备【{$val}】产品与调拨产品不一致！！");
                }
            }
        } else {
            $this->error("缺少调拨设备");
        }

        $toType = 2;
        $confirmTime = time();

        $result = false;
        Db::startTrans();
        try {
            $allocation = new Allocation();
            $allocation->type = $type;
            $allocation->from_type = 2;
            $allocation->from = $this->auth->id;
            $allocation->to_type = $toType;
            $allocation->to = $to;
            $allocation->policy_id = 0;
            $allocation->product_id = $productId;
            $allocation->number = $countSn;
            $allocation->data_type = 3;
            $allocation->sn = implode(",", $sn);
            $allocation->remark_content = $remark;
            $allocation->confirm_type = 1;
            $allocation->confirm_time = $confirmTime;
            $allocation->save();

            $data = [];
            foreach ($sn as $key => $val){
                $data[] = [
                    "allocation_id" => $allocation->id,
                    "sn" => $val
                ];
            }

            //保存调拨明细
            $details = new \app\common\model\AllocationDetails();
            $details->saveAll($data);

            //更新设备归属
            Tools::updateEquip($productId,$data,$toType,$to,$confirmTime);

            //操作订单
            $orderProduct->status = 2;
            $orderProduct->allocation_id = $allocation->id;
            $orderProduct->save();

            if(\app\common\func\Order::getOrderProductCount($orderProduct->order_id) == \app\common\func\Order::getOrderProductFinishCount($orderProduct->order_id)){
                $order->pay_state = 2;
                $order->finish_time = time();
                $order->save();

                if(in_array($order->pay_type,[1,2])){//认购量购买，不增加余额
                    $option = [
                        "uid"		=> $this->auth->id, // 收入 或 支出 代理ID
                        "typs"		=> 10, // 变更类型 1=分润,2=流量卡,3=达标,4=借款,5=还款,6=赠送,7=提现,8=认购,9=调价，10=采购
                        "isChg" 	=> 1, // 1 收入
                        "remark" 	=> "完成下级订单收益",	// 备注  => 没有备注传空字符串
                        "chgAmt" 	=> $order->pay_price,	// 变更金额
                        "ids" 		=> $order->id,	// 操作订单主ID | 分润、达标、流量卡 传入产品ID
                    ];
                    \app\common\controller\Balance::instance()->add_and_logs($option);
                }
            }

            $result = true;

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
        }

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //政策详情
    public function getPolicyDetails()
    {
        $policyId = $this->request->post('policy_id');

        if (!$policyId) {
            $this->error("缺少参数！");
        }

        $info = [];
        try {
            $policy = Lib::getPolicy($policyId);

            $profit = Lib::getProfitById($policy->profit_id);
            $cash = Lib::getCashById($policy->cash_id);
            $flow = Lib::getFlowById($policy->flow_id);
            $standard = Lib::getStandardByIds($policy->stardard_id);

            $settingList = [];
            $setting = Lib::getProfitDetails($profit->id);
            if (count($setting) > 0) {
                foreach ($setting as $key => $val) {
                    $settingList[] = [
                        "tran" => Lib::getTransaction($val->transaction_type_id)->name,
                        "card" => Tools::$cardType[$val->card_type],
                        "rate" => Lib::getRate($val->rate_id)->name,
                        "channel" => Lib::getChannelById($val->channel_id)->name,
                        "value" => $val->profit_rate,
                    ];
                }
            }

            $info["policy_title"] = $policy->title;
            $info["product"] = Lib::getProductById($profit->product_id);
            $info["profit"] = [
                "profit" => $profit,
                "rate" => Lib::getRateList(explode(",", $profit->rate_ids)),
                "tran" => Lib::getTransactionTypeBYIds($profit->transaction_type_ids),
                "card" => Tools::getCardTypeObj($profit->card_type),
                "channel" => Lib::getChannelByIds($profit->channel_ids),
                "setting" => $settingList,
            ];
            $info["cash"] = [
                "cash" => $cash,
                "rate" => Lib::getRateList(explode(",", $cash->rate_ids)),
                "tran" => Lib::getTransactionTypeBYIds($cash->transaction_type_ids),
                "card" => Tools::getCardTypeObj($cash->card_type),
                "channel" => Lib::getChannelByIds($cash->channel_ids),
            ];
            $info["flow"] = [
                "flow" => $flow
            ];
            if (count($standard) > 0) {
                foreach ($standard as $key => $val) {
                    $info["standard"][] = [
                        "standard" => $val,
                        "rate" => Lib::getRateList(explode(",", $val->rate_ids)),
                        "tran" => Lib::getTransactionTypeBYIds($val->transaction_type_ids),
                        "card" => Tools::getCardTypeObj($val->card_type),
                        "channel" => Lib::getChannelByIds($val->channel_ids),
                    ];
                }
            } else {
                $info["standard"] = [];
            }
        } catch (\Exception $e) {
            $info = [];
        }

        $this->success("政策详情", $info);
    }

    //政策列表
    public function getPolicyList()
    {
        $pageSize = $this->request->post('page_size', 15);
        $search = $this->request->post('search');

        $list = Lib::getPolicyList(2, $this->auth->id, $search, $pageSize);
        if (count($list) > 0) {
            foreach ($list as $key => $val) {
                $profit = Lib::getProfitByPolicy($val->id);
                $val->product = Lib::getProductById($profit['product_id']);
            }
        }

        $this->success("政策列表", $list);
    }

    //政策保存
    public function savePolicy()
    {
        $title = $this->request->post('title');
        $profitId = $this->request->post('profit_id');
        $cashId = $this->request->post('cash_id');
        $flowId = $this->request->post('flow_id');
        $standardId = $this->request->post('standard_id/a');

        if (!$title || !$profitId || !$cashId || !$flowId || !$standardId) {
            $this->error("缺少必要参数");
        }

        $policy = new Policy();
        $policy->main_type = 2;
        $policy->main_id = $this->auth->id;
        $policy->title = $title;
        $policy->profit_id = $profitId;
        $policy->cash_id = $cashId;
        $policy->flow_id = $flowId;
        $policy->stardard_id = implode(",", $standardId);
        $result = $policy->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //达标列表
    public function getStandardList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getStandardList(2, $this->auth->id, $pageSize);
        foreach ($list as $key => $val) {
            $val->product = Lib::getProductById($val->product_id);
            $val->rate = Lib::getRateList(explode(",", $val->rate_ids));
            $val->tran = Lib::getTransactionTypeBYIds($val->transaction_type_ids);
            $val->card = Tools::getCardTypeObj($val->card_type);
            $val->channel = Lib::getChannelByIds($val->channel_ids);
        }

        $this->success("达标列表", $list);
    }

    //达标保存
    public function saveStandard()
    {
        $title = $this->request->post('title');
        $dayLimit = $this->request->post('day_limit');
        $money = $this->request->post('money');
        $reward = $this->request->post('reward');

        if (!$title || !$dayLimit || !$money || is_null($reward)) {
            $this->error("缺少必要参数");
        }

        $standard = new Stardard();
        $standard->main_type = 2;
        $standard->main_id = $this->auth->id;
        $standard->title = $title;
        $standard->day_limit = $dayLimit;
        $standard->money = $money;
        $standard->reward = $reward;
        $result = $standard->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //流量卡列表
    public function getFlowList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getFlowList(2, $this->auth->id, $pageSize);
        foreach ($list as $key => $val) {
            $val->product = Lib::getProductById($val->product_id);
        }

        $this->success("流量卡列表", $list);
    }

    //流量卡保存
    public function saveFlow()
    {
        $title = $this->request->post('title');
        $reward = $this->request->post('reward');
        $productId = $this->request->post('product_id');

        if (!$title || is_null($reward)) {
            $this->error("缺少必要参数");
        }

        $flow = new Flow();
        $flow->main_type = 2;
        $flow->main_id = $this->auth->id;
        $flow->title = $title;
        $flow->reward = $reward;
        $flow->product_id = $productId;
        $result = $flow->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //返现列表
    public function getCashList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getCashList(2, $this->auth->id, $pageSize);
        foreach ($list as $key => $val) {
            $val->product = Lib::getProductById($val->product_id);
            $val->rate = Lib::getRateList(explode(",", $val->rate_ids));
            $val->tran = Lib::getTransactionTypeBYIds($val->transaction_type_ids);
            $val->card = Tools::getCardTypeObj($val->card_type);
            $val->channel = Lib::getChannelByIds($val->channel_ids);
        }

        $this->success("返现列表", $list);
    }

    //返现设置保存
    public function saveCash()
    {
        $title = $this->request->post('title');
        $dayLimit = $this->request->post('day_limit');
        $money = $this->request->post('money');
        $reward = $this->request->post('reward');
        $productId = $this->request->post('product_id');
        $rateIds = $this->request->post('rate_ids');
        $tran = $this->request->post('transaction_type_ids');
        $cardType = $this->request->post('card_type');
        $channel = $this->request->post('channel_ids');

        if (!$title || !$dayLimit || !$money || is_null($reward)) {
            $this->error("缺少必要参数");
        }

        $cash = new Cash();
        $cash->main_type = 2;
        $cash->main_id = $this->auth->id;
        $cash->title = $title;
        $cash->day_limit = $dayLimit;
        $cash->money = $money;
        $cash->reward = $reward;
        $cash->product_id = $productId;
        $cash->rate_ids = $rateIds;
        $cash->transaction_type_ids = $tran;
        $cash->card_type = $cardType;
        $cash->channel_ids = $channel;
        $result = $cash->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //分润列表
    public function getProfitList()
    {
        $pageSize = $this->request->post('page_size', 15);
        $search = $this->request->post('search');

        $list = Lib::getProfitList(2, $this->auth->id, $search, $pageSize);
        foreach ($list as $key => $val) {
            $val->product = Lib::getProductById($val->product_id);
            $val->rate = Lib::getRateList(explode(",", $val->rate_ids));
            $val->tran = Lib::getTransactionTypeBYIds($val->transaction_type_ids);
            $val->card = Tools::getCardTypeObj($val->card_type);
            $val->channel = Lib::getChannelByIds($val->channel_ids);
        }

        $this->success("分润列表", $list);
    }

    public function deletePolicy()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $count = Lib::getPolicyRelationByPolicy($id);
        if ($count > 0) {
            $this->error("已绑定设备，不可删除！");
        }

        $policy = Lib::getPolicy($id);
        $policy->status = 2;
        $result = $policy->save();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function deleteStandard()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $policyList = Lib::getPolicyBySetting("standard", $id);

        if (count($policyList) > 0) {
            $this->error("已绑定政策，不可删除！");
        }

        $standard = Lib::getStandardById($id);
        $standard->status = 2;
        $result = $standard->save();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function deleteFlow()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $policyList = Lib::getPolicyBySetting("flow", $id);

        if (count($policyList) > 0) {
            $this->error("已绑定政策，不可删除！");
        }

        $flow = Lib::getFlowById($id);
        $flow->status = 2;
        $result = $flow->save();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function deleteCash()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $policyList = Lib::getPolicyBySetting("cash", $id);

        if (count($policyList) > 0) {
            $this->error("已绑定政策，不可删除！");
        }

        $cash = Lib::getCashById($id);
        $cash->status = 2;
        $result = $cash->save();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function deleteProfit()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $policyList = Lib::getPolicyBySetting("profit", $id);

        if (count($policyList) > 0) {
            $this->error("已绑定政策，不可删除！");
        }

        $profitObj = Lib::getProfitById($id);
        $profitObj->status = 2;
        $result = $profitObj->save();
        if ($result) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function getProfit()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $profitObj = Lib::getProfitById($id);

        if ($profitObj) {
            $this->success("分润内容", $profitObj);
        } else {
            $this->error("未找到信息");
        }
    }

    //分润创建
    public function saveProfit()
    {
        $id = $this->request->post('id', 0);
        $title = $this->request->post('title');
        $productId = $this->request->post('product_id');
        $rateIds = $this->request->post('rate_ids');
        $tranTypeIds = $this->request->post('transaction_type_id');
        $cardType = $this->request->post('card_type');
        $superProfit = $this->request->post('profit_id');
        $channelId = $this->request->post('channel_id');

        if (!$title || !$productId || !$rateIds || !$tranTypeIds || !$cardType || !$channelId) {
            $this->error("缺少必要参数");
        }

        if ($id > 0) {
            $profit = Lib::getProfitById($id);
        } else {
            $profit = new Profit();
        }
        $profit->main_type = 2;
        $profit->main_id = $this->auth->id;
        $profit->title = $title;
        $profit->product_id = $productId;
        $profit->rate_ids = $rateIds;
        $profit->transaction_type_ids = $tranTypeIds;
        $profit->card_type = $cardType;
        $profit->channel_ids = $channelId;
        $profit->super_profit = $superProfit;
        $result = $profit->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败");
        }
    }

    //分润设置选项
    public function getProfitSetting()
    {
        $profit = Lib::getProfitByUser(2, $this->auth->id);

        $list = [];

        if (count($profit) > 0) {
            foreach ($profit as $key => $val) {
                $productList = Lib::getProductById($val['product_id']);
                $productList->rate_list = Lib::getRateListByIds($val['rate_ids']);
                $productList->tran_list = Lib::getTransactionTypeBYIds($val['transaction_type_ids']);
                $productList->card_type_list = Tools::getCardTypeObj($val['card_type']);
                $productList->channel_list = Lib::getChannelByIds($val['channel_ids']);
                //                $rateList = Lib::getRateListByIds($val['rate_ids']);
                //                $tranList = Lib::getTransactionTypeBYIds($val['transaction_type_ids']);
                //                $cardTypeList = Tools::getCardTypeObj($val['card_type']);

                $list[] = [
                    "product" => $productList,
                    //                    "rate_list" => $rateList,
                    //                    "tran_list" => $tranList,
                    //                    "card_type_list" => $cardTypeList,
                ];
            }
        }

        $this->success("分润设置选项", $list);
    }

    //分润设置详情
    public function getProfitDetails()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少必要参数！");
        }

        $profitObj = Lib::getProfitById($id);
        if (!$profitObj->card_type || !$profitObj->transaction_type_ids || !$profitObj->rate_ids || !$profitObj->channel_ids) {
            $this->error("存在未设置项，请重新添加！");
        }

        $data = [];
        foreach (Tools::getCardTypeList(explode(",", $profitObj->card_type)) as $key => $val) {
            foreach (Lib::getTransactionList(explode(",", $profitObj->transaction_type_ids)) as $k => $v) {
                foreach (Lib::getRateList(explode(",", $profitObj->rate_ids)) as $k1 => $v1) {
                    foreach (Lib::getChannelByIds($profitObj->channel_ids) as $k2 => $v2) {
                        $profit = Lib::getProfitDetailsByParams($profitObj->id, $key, $v->id, $v1->id, $v2->id);
                        if ($profit) {
                            $profitVal = $profit->profit_rate;
                        } else {
                            $profitVal = "";
                        }
                        $obj = Lib::getProfitRateByParams($profitObj->super_profit, $key, $v->id, $v1->id, $v2->id);
                        $max = $obj ? $obj["profit_rate"] : 0;

                        $data[] = [
                            "card" => $key,
                            "card_text" => Tools::$cardType[$key],
                            "tran" => $v->id,
                            "tran_text" => $v->name,
                            "rate" => $v1->id,
                            "rate_text" => $v1->name,
                            "channel" => $v2->id,
                            "channel_text" => $v2->name,
                            "profit" => $profitVal,
                            "max" => $max,
                        ];
                    }
                }
            }
        }
        if (count($data) == 0) {
            $this->error("请联系上级设置");
        }

        $this->success("分润详情", $data);
    }

    //分润设置保存
    public function saveProfitDetails()
    {
        $id = $this->request->post('id');
        $card = $this->request->post('card/a');
        $tran = $this->request->post('tran/a');
        $rate = $this->request->post('rate/a');
        $channel = $this->request->post('channel/a');
        $profit = $this->request->post('profit/a');

        $profitObj = Lib::getProfitById($id);

        if (!$profitObj) {
            $this->error("未找到分润设置！");
        }

        for ($i = 0; $i < count($profit); $i++) {
            $detail = Lib::getProfitDetailsByParams($profitObj->id, $card[$i], $tran[$i], $rate[$i], $channel[$i]);
            if ($detail) {
                if ($detail->profit_rate != $profit[$i]) {
                    $detail->profit_rate = $profit[$i];
                    $detail->save();
                } else {
                    continue;
                }
            } else {
                $details = new \app\common\model\ProfitDetails();
                $details->profit_id = $profitObj->id;
                $details->card_type = $card[$i];
                $details->transaction_type_id = $tran[$i];
                $details->rate_id = $rate[$i];
                $details->channel_id = $channel[$i];
                $details->profit_rate = $profit[$i];
                $details->save();
            }
        }

        $this->success("设置成功！");
    }

    //下级用户
    public function getChild()
    {
        $list = Lib::getChildUser(2, $this->auth->id);

        $this->success("下级用户", $list);
    }

    // ------------------------------------------------------- 政策 --------------------------------------------------------

    /**
     * 返回自己产品 + 政策
     */
    public function getProductAndPolicy()
    {
        $data = [];
        $product = lib::getEquipProduct(2, $this->auth->id);
        foreach ($product as $key => $val) {
            $data[$key] = [
                "id" => $val["id"],
                "name" => $val["name"],
                "policy" => []
            ];
            $policy = lib::getProductPolicy(2, $this->auth->id, $val["id"]);
            foreach ($policy as $vals) {
                $data[$key]["policy"][] = [
                    "id" => $vals["id"],
                    "title" => $vals["title"]
                ];
            }
        }
        $this->success("获取成功", $data);
    }

    /**
     * 根据产品ID获取自己政策
     */
    public function getProductPolicy()
    {
        $productId = $this->request->post('product_id');
        $data = lib::getProductPolicy(2, $this->auth->id, $productId);
        $this->success("获取成功", $data);
    }

    /**
     * 获取我给代理设置的政策
     */
    public function getMyAgencyPolicy()
    {
        $productId = $this->request->post('product_id');
        $data = lib::getSubordinatePolicy($productId, 2, $this->auth->id);
        $this->success("获取成功", $data);
    }

    /**
     * 获取政策详情
     */
    public function getPolicyDetail()
    {
        $policyId = $this->request->post('policy_id');
        $data = Lib::getPolicyDetail($policyId);
        $data->rate = Lib::getRateList(explode(",", $data->rate_ids));
        $data->tran = Lib::getTransactionTypeBYIds($data->transaction_type_ids);
        $data->card = Tools::getCardTypeObj($data->card_type);
        $data->channel = Lib::getChannelByIds($data->channel_ids);
        $this->success("获取成功", $data);
    }

    /**
     * 获取我的产品
     */
    public function getMyProduct()
    {
        $data = Lib::getMyProduct5($this->auth->id, 2);
        $product = [];
        foreach ($data as $val) {
            if (isset($val["id"]) && !empty($val["id"]) && $val["id"] > 0) {
                $product[] = $val;

            }
        }
        $this->success("获取成功", $product);
    }

    /**
     * 根据产品获取我的默认政策 - 详情
     */
    public function getMyDefaultPolicy()
    {
        $productId = $this->request->post('product_id');
        $policy = PolicyRelation::where(["main_type" => 2, "main_id" => $this->auth->id, "product_id" => $productId, "default" => 1])->find();
        if (isset($policy->policy_id) && $policy->policy_id > 0) {
            $data = Lib::getPolicyDetail($policy->policy_id);
            $data->rate = Lib::getRateList(explode(",", $data->rate_ids));
            $data->tran = Lib::getTransactionTypeBYIds($data->transaction_type_ids);
            $data->card = Tools::getCardTypeObj($data->card_type);
            $data->channel = Lib::getChannelByIds($data->channel_ids);
            $this->success("获取成功", $data);
        } else {
            $this->error("该产品未设置政策！");
        }
    }

    /**
     * 获取APP版本信息
     */
    public function getAppVersion()
    {
        $data = AppVersion::where('status', 1)->order('create_time desc')->find();
        $this->success("版本信息", $data);
    }

    public function getStandardRecord(){
        $productId = $this->request->post('product_id');

        $equipList = Lib::getMyEquip(2,$this->auth->id,$productId);

        $list = [];
        if(count($equipList) > 0){
            foreach ($equipList as $key => $val){
                $list[] = [
                    "sn" => $val->sn,
                    "binding_time" => date("Y-m-d",$val->binding_time),
                    "standard" => Lib::getEquipStandardRecord($val->sn,$val->binding_time),
                    "user_name" => $val->user_info
                ];
            }
        }

        $this->success("达标列表",$list);
    }

    /**
     * 修改政策名称
     */
    public function updatePolicyTitle()
    {
        $id = $this->request->post('id', '');
        $title = $this->request->post('title', '');

        if (!empty($id) && !empty($title)) {
            Policy::where(['id' => $id])->update(["title" => $title]);
            $this->success("修改成功");
        } else {
            $this->error("参数错误！");
        }
    }
}
